<?php

namespace app\admin\controller\facrm;

use app\common\controller\Backend;
use app\admin\model\AuthGroup;
use fast\Tree;
/**
 * 共有的一些不需要权限的接口
 * @internal
 */
class Common extends Backend
{
    protected $noNeedRight = ['*'];
    public function _initialize()
    {
        parent::_initialize();
        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);
    }

    /**
     * 下拉选择
     * @fun
     * @Internal
     */
    public function selectpage(){
        $modellist=['admin'];
        $model = $this->request->param('model');
        if (!$this->request->request('keyField')){
            $this->error("访问出错");
        }
        if (!in_array($model,$modellist))
            $this->error("非法访问");

        $this->model = model($model);
        $type = $this->request->param('type');


        switch ($model){
            case 'admin':
				$custom=['status'=>'normal'];
                if ($type != "all") {
                    $childrenAdminIds = $this->auth->getChildrenAdminIds(true);
					$custom['id']= ['in', $childrenAdminIds];
                }
				 $this->request->request(['custom' => $custom]);
                break;
        }
        return parent::selectpage();
    }

	/**
     * 组
     * @fun
     * @Internal
     */
	public function group(){
		 $this->model = model('AuthGroup');

        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);

        $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();

        Tree::instance()->init($groupList);
        $groupList = [];
        if ($this->auth->isSuperAdmin()) {
            $groupList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
        } else {
            $groups = $this->auth->getGroups();
            $groupIds = [];
            foreach ($groups as $m => $n) {
                if (in_array($n['id'], $groupIds) || in_array($n['pid'], $groupIds)) {
                    continue;
                }
                $groupList = array_merge($groupList, Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['pid'])));
                foreach ($groupList as $index => $item) {
                    $groupIds[] = $item['id'];
                }
            }
        }
		
		
		//如果发送的来源是Selectpage，则转发到Selectpage
		$searchValue = $this->request->request("searchValue");
		$search = $this->request->request("search");

		//构造父类select列表选项数据
		$list = [];
		if ($search||$searchValue) {

			foreach ($groupList as $k => &$v) {

				if ($search&&stripos($v['name'], $search) !== false) {
					$list[] = $v;
				}
				if ($searchValue&&in_array($v['id'], explode(',',$searchValue)) !== false) {
					$v['name']=preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)/", " ", strip_tags($v['name'])); //过滤空格
					$list[] = $v;
				}
			}
		} else {
			$list = $groupList;
		}

		$list = array_values($list);

		$total = count($list);
		$result = array("total" => $total, "rows" => $list);

		return json($result);
		
	}
    public function pageList(){
        $pageList = [
            ['path' => '/pages/index/index', 'name' => '首页'],
            ['path' => '/pages/client/index', 'name' => '客户列表'],
            ['path' => '/pages/business/index', 'name' => '商机列表'],
            ['path' => '/pages/presentation/index', 'name' => '数据统计'],
            ['path' => '/pages/clues/index', 'name' => '线索列表'],
            ['path' => '/pages/client/clientSet/clientSet', 'name' => '新建客户'],
            ['path' => '/pages/business/addBusiness/index', 'name' => '新建商机'],
            ['path' => '/pages/contract/index', 'name' => '新建合同'],
            ['path' => '/pages/contract/list/index', 'name' => '合同列表'],
            ['path' => '/pages/receivables/list', 'name' => '回款列表'],
            ['path' => '/pages/backlog/list', 'name' => '待审批列表（?type=0或type=1）'],
            ['path' => '/pages/highSeas/index', 'name' => '公海'],
            ['path' => '/pages/more/index', 'name' => '更多功能'],
            ['path' => '/pages/performance/index', 'name' => '业绩设置'],
            ['path' => '/pages/receivables/manage', 'name' => '新建回款'],

        ];
        $this->view->assign('pageList', $pageList);
        return $this->view->fetch('facrm/common/pages');
    }

    /**
     * 生成二维码
     * @ApiSummary("直接返回图片流")
     * @ApiParams(name="text", type="string", required=true, description="要生成二维码的数据")
     * @ApiBody("返回的二维码数据");
     */
    public function qrcode()
    {
        $text = $this->request->request('text');
        $pathname = RUNTIME_PATH . "code" . DS;
        if (!is_dir($pathname)) {
            mkdir($pathname, 0755, true);
        }

        $img_file = $pathname . md5($text) . ".png";
        if (file_exists($img_file)) {
            $contents = file_get_contents($img_file);
            header('Content-type:image/png');
            echo $contents;
            exit();
        }
        $qr = \addons\facrm\library\QRCode::getMinimumQRCode($text);
        $im = $qr->createImage(8, 5);
        header("Content-type: image/png");
        imagepng($im, $img_file);
        imagedestroy($im);
        if (file_exists($img_file)) {
            $contents = file_get_contents($img_file);
            header('Content-type:image/png');
            echo $contents;
            exit();
        }
        exit();
    }



}
